package com.hencoderplus.demo1;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * hencoderplus
 * Created by lzw on 2018/11/1. 15:33:05
 * 邮箱：632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public class TagLayout extends ViewGroup {
    private static final String TAG = "TagLayout";
    private List<Rect> children = new ArrayList<>();


    public TagLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int linewidthUsed = 0;
        int widthUsed = 0;
        int heightUsed = 0;
        int lineMaxHeight = 0;
        int specWidth = MeasureSpec.getSize(widthMeasureSpec);
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            measureChildWithMargins(child,widthMeasureSpec,0,heightMeasureSpec,heightUsed);
            if (mode!=MeasureSpec.UNSPECIFIED&&linewidthUsed+child.getMeasuredWidth() > specWidth){
                linewidthUsed = 0;
                heightUsed += lineMaxHeight;
                lineMaxHeight=0;
                measureChildWithMargins(child,widthMeasureSpec,0,heightMeasureSpec,heightUsed);
            }

            Rect childBound;
            if (children.size()<=i){
                childBound = new Rect();
                children.add(childBound);
            }else{
                 childBound = children.get(i);
            }
            childBound.set(linewidthUsed,heightUsed,linewidthUsed+child.getMeasuredWidth(),heightUsed+child.getMeasuredHeight());
            linewidthUsed += child.getMeasuredWidth();
            widthUsed = Math.max(widthUsed,linewidthUsed);
            lineMaxHeight = Math.max(lineMaxHeight,child.getMeasuredHeight());
        }
        Log.i(TAG, "onMeasure: linewidthUsed="+linewidthUsed+" heightUsed="+heightUsed);
        int width = widthUsed;
        int height = lineMaxHeight+heightUsed;
        setMeasuredDimension(width,height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
                child.layout(children.get(i).left, children.get(i).top, children.get(i).right,
                        children.get(i).bottom);
        }

    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet p) {
        return new MarginLayoutParams(getContext(),p);
    }
}
